<template>
  <div class="submission-history">
    <h3>提交历史 ({{ total }} 条记录)</h3>

    <div class="filter-bar">
      <el-select
          v-model="statusFilter"
          placeholder="筛选状态"
          size="default"
          clearable
          @change="handleFilterChange"
          class="filter-select"
      >
        <el-option label="通过 (Accepted)" :value="1" />
        <el-option label="答案错误 (Wrong Answer)" :value="2" />
        <el-option label="编译错误 (Compile Error)" :value="3" />
        <el-option label="内存溢出 (Out Of Memory)" :value="4" />
        <el-option label="超时 (Time Limit Exceeded)" :value="5" />
        <el-option label="运行错误 (Runtime Error)" :value="10" />
        <el-option label="等待中 (Waiting)" :value="7" />
      </el-select>

      <el-select
          v-model="languageFilter"
          placeholder="筛选语言"
          size="default"
          clearable
          @change="handleFilterChange"
          class="filter-select"
      >
        <el-option label="Java" value="java" />
        <el-option label="C++" value="cpp" />
        <el-option label="Python" value="python" />
        <el-option label="JavaScript" value="javascript" />
      </el-select>
    </div>

    <el-table
        :data="submissionsList"
        v-loading="loading"
        style="width: 100%"
        class="submission-table"
    >
      <el-table-column prop="questionId" label="ID" width="100" />

      <el-table-column label="题目名称">
        <template #default="scope">
          <el-link type="primary" @click="goToQuestion(scope.row.questionId)">
            {{ scope.row.questionVO?.title }}
          </el-link>
        </template>
      </el-table-column>

      <el-table-column label="状态" width="180">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.accepted)" size="default">
            {{ getStatusText(scope.row.accepted) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="language" label="语言" width="120" />

      <el-table-column label="耗时" width="120">
        <template #default="scope">
          {{ scope.row.judgeInfo?.time ?? "N/A" }} ms
        </template>
      </el-table-column>

      <el-table-column label="提交时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="120" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleViewCode(scope.row)">
            查看代码
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
      />
    </div>

    <el-dialog
        v-model="codeDialogVisible"
        :title="`查看提交 #${selectedSubmission?.id} 的代码`"
        width="60%"
        top="5vh"
        destroy-on-close
    >
      <div v-loading="codeLoading" class="code-container">
        <pre><code ref="codeBlockRef" class="hljs" :class="selectedSubmission?.language">{{ submissionCode }}</code></pre>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import {
  QuestionControllerService,
  type QuestionSubmitQueryRequest,
  type QuestionSubmitVO,
} from "../../../generated";

// ⭐ 3. 导入 highlight.js 核心、样式和语言包
import hljs from "highlight.js/lib/core";
import java from "highlight.js/lib/languages/java";
import cpp from "highlight.js/lib/languages/cpp";
import python from "highlight.js/lib/languages/python";
import javascript from "highlight.js/lib/languages/javascript";
// 引入一个你喜欢的主题样式，例如 github-dark
import "highlight.js/styles/github-dark.css";

// ⭐ 4. 注册语言
hljs.registerLanguage("java", java);
hljs.registerLanguage("cpp", cpp);
hljs.registerLanguage("python", python);
hljs.registerLanguage("javascript", javascript);

const router = useRouter();

const statusFilter = ref<number | null>(null);
const languageFilter = ref<string | null>(null);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(30);
const total = ref(0);
const submissionsList = ref<QuestionSubmitVO[]>([]);

// ⭐ 5. 新增对话框所需的状态变量
const codeDialogVisible = ref(false); // 对话框可见性
const codeLoading = ref(false); // 代码加载状态
const submissionCode = ref(""); // 代码内容
const selectedSubmission = ref<QuestionSubmitVO | null>(null); // 当前选中的行
const codeBlockRef = ref<HTMLElement | null>(null); // 代码块的 DOM 引用

const getStatusText = (status?: number) => {
  // ... 此处代码无变化
  switch (status) {
    case 0: return '未提交';
    case 1: return 'Accepted';
    case 2: return 'Wrong Answer';
    case 3: return 'Compile Error';
    case 4: return 'Memory Limit Exceeded';
    case 5: return 'Time Limit Exceeded';
    case 6: return 'Presentation Error';
    case 7: return 'Waiting';
    case 8: return 'Output Limit Exceeded';
    case 9: return 'Dangerous Operation';
    case 10: return 'Runtime Error';
    case 11: return 'System Error';
    default: return '未知状态';
  }
};

const getStatusTagType = (status?: number) => {
  // ... 此处代码无变化
  switch (status) {
    case 1: return 'success'; // Accepted
    case 2: return 'danger';  // Wrong Answer
    case 3: return 'info';    // Compile Error
    case 4:
    case 5:
    case 10:
    case 11:
      return 'warning'; // MLE, TLE, RE, System Error
    default:
      return 'info';    // 其他所有状态
  }
};

const loadSubmissions = async () => {
  loading.value = true;
  try {
    const requestBody: QuestionSubmitQueryRequest = {
      current: currentPage.value,
      pageSize: pageSize.value,
      language: languageFilter.value || undefined,
      // ⭐ 修正：此处的 accepted 应该为 status
      accepted: statusFilter.value ?? undefined,
      sortOrder: 'desc',
      sortField: 'createTime'
    };

    // 这里应该是获取列表的接口
    const res = await QuestionControllerService.listQuestionVoMyHistorySubmitByPage(requestBody);

    if (res.code === 0) {
      submissionsList.value = res.data?.records || [];
      total.value = Number(res.data?.total) || 0;
    } else {
      ElMessage.error("加载提交历史失败：" + res.message);
    }
  } catch (error: any) {
    ElMessage.error("网络错误，无法加载提交历史");
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// ⭐ 6. 新增“查看代码”的事件处理函数
// ⭐ 6. 更新后的“查看代码”事件处理函数（无需网络请求）
const handleViewCode = (row: QuestionSubmitVO) => {
  // 1. 保存当前行数据，并打开对话框
  selectedSubmission.value = row;
  codeDialogVisible.value = true;

  // 2. 直接从 row 对象中获取代码
  //    如果 row.code 可能为 null 或 undefined，提供一个后备提示
  submissionCode.value = row.code || "无代码信息";

  // 3. 等待 Vue 将代码渲染到 DOM 上后，再执行高亮
  nextTick(() => {
    if (codeBlockRef.value) {
      hljs.highlightElement(codeBlockRef.value);
    }
  });
};

const formatDate = (dateString?: string): string => {
  // ... 此处代码无变化
  if (!dateString) {
    return 'N/A';
  }
  const now = new Date();
  const date = new Date(dateString);
  const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);

  const secondsInMinute = 60;
  const secondsInHour = 60 * secondsInMinute;
  const secondsInDay = 24 * secondsInHour;

  if (diffInSeconds < secondsInMinute) {
    return '刚刚';
  }
  if (diffInSeconds < secondsInHour) {
    return `${Math.floor(diffInSeconds / secondsInMinute)} 分钟前`;
  }
  if (diffInSeconds < secondsInDay) {
    return `${Math.floor(diffInSeconds / secondsInHour)} 小时前`;
  }

  // 对于更早的日期，格式化为 "YYYY-MM-DD HH:mm"
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

const handlePageChange = (page: number) => {
  currentPage.value = page;
  loadSubmissions();
};

const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  loadSubmissions();
};

const handleFilterChange = () => {
  currentPage.value = 1;
  loadSubmissions();
};

const goToQuestion = (questionId?: number) => {
  if (!questionId) return;
  router.push(`/questions/detail/${questionId}`);
};

onMounted(() => {
  loadSubmissions();
});
</script>

<style scoped>
/* ... 原有样式无变化 ... */
.submission-history {
  padding: 20px;
}
h3 {
  margin-bottom: 25px;
  font-size: 20px;
  font-weight: 500;
  color: #333;
}
.filter-bar {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}
.filter-select {
  width: 220px;
}
.submission-table {
  --el-table-border-color: #f0f0f0;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end; /* 分页器靠右对齐 */
}

/* ⭐ 7. 新增代码容器样式 */
.code-container {
  background: #282c34; /* 代码块背景色，匹配 github-dark 主题 */
  border-radius: 4px;
  padding: 1rem;
  max-height: 70vh; /* 限制最大高度，超出则滚动 */
  overflow: auto;
  min-height: 200px;
}
.code-container code {
  font-family: Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace;
  font-size: 14px;
  white-space: pre-wrap; /* 自动换行 */
  word-break: break-all;
}
</style>